<template>
  <jc-bar>
    <template #default>
      <v-btn aria-label="返回上一页" v-if="!share" icon @click="prev">
        <j-icon size="20">mdi-arrow-left</j-icon>
      </v-btn>
      <v-btn v-else icon @click="$router.replace({ path: '/home' })">
        <j-icon size="20">mdi-home</j-icon>
      </v-btn>

      <v-spacer></v-spacer>
      <span class="text-title" :aria-label="`歌单标题${title}`" role="title">{{ title }}</span>
      <v-spacer></v-spacer>
      <v-btn aria-label="分享" icon @click="shareConfig">
        <j-icon size="20">mdi-share-variant</j-icon>
      </v-btn>
      <template v-if="!share">
        <v-btn aria-label="添加曲目" icon @click="$router.push({ path: '/seachersgb', query: { gedanid: gedanId } })"
          ><j-icon size="20">mdi-plus</j-icon></v-btn
        >
      </template>
    </template>
  </jc-bar>

  <div
    v-sort="{
      handle: '.trag-handler',
      onEnd: (evt) => handleSortEnd(evt),
    }"
    class="h-[calc(100%)] overflow-auto"
  >
    <v-list-item v-for="item in list" :key="item._id" class="px-4 cursor-pointer">
      <div class="flex justify-between py-2">
        <div @click="toDetail(item)" class="flex-1">
          <div>
            <span class="text-subtitle mr-2" v-if="item.xuhao">{{ item.xuhao }}</span>
            <span class="text-title">{{ item.mulu }} </span>
          </div>
          <div class="text-subtitle">
            {{ item.shijiName }}
          </div>
        </div>

        <div class="flex" v-if="isSelf">
          <v-btn class="trag-handler" aria-label="拖拽控件" icon :elevation="0" color="grand lighten-1" variant="text"
            ><j-icon color="rgb(var(--v-title))" size="20">mdi-altimeter</j-icon></v-btn
          >

          <v-btn
            aria-label="删除"
            icon
            :elevation="0"
            @click.stop="
              dialogVisable = true;
              selectItemId = item._id;
            "
            variant="text"
            ><j-icon color="rgb(var(--v-title))" size="20">mdi-trash-can-outline</j-icon></v-btn
          >
        </div>
      </div>
    </v-list-item>

    <div class="transparent my-4 w-100 d-flex justify-center gap-x-4">
      <v-btn
        type="primary"
        color="red light-2"
        class="white--text"
        rounded
        @click="
          $router.push({
            path: '/seachersgb',
            query: { gedanid: gedanId },
          })
        "
        v-if="!share && isSelf"
      >
        添加
      </v-btn>
      <v-btn type="primary" v-if="!isSelf" color="red light-2" class="white--text ml-2" rounded @click="saveAsMe">
        收藏歌单
      </v-btn>

      <DownLongGePu
        v-if="list.length > 0"
        :ids="list"
        className="ml-2"
        :title="`${title}.jpg`"
        color="red light-2"
        :erCodeUrl="copyurl"
        :id="id"
      >
        下载歌谱
      </DownLongGePu>
      <v-btn type="primary" color="red light-2" class="white--text ml-2" rounded @click="copyId"> 复制ID </v-btn>
    </div>
  </div>

  <input type="text" v-if="copyurlvisble" ref="copyurlinput" v-model="copyurl" />
  <jc-confirm-box
    msg="确认要删除这条数据吗？"
    @jcchange="confirmChange"
    :show="dialogVisable"
    @confirm="handleRemove"
  ></jc-confirm-box>

  <v-dialog v-model="sharePropVisable">
    <share-prop
      v-if="sharePropVisable"
      :copy-url="copyurl"
      :title="title"
      :avatar-url="userInfo.avatarUrl"
      :nick-name="userInfo.nickName"
      :prop-visable="sharePropVisable"
    ></share-prop>
  </v-dialog>
</template>

<script>
import { alert } from "@/utils/utils";
import JcBar from "@/layout/JcBar";
import { gedanController } from "@/api/cloudbase-user-action-log";
import JcConfirmBox from "@/jcui/JcConfirmationBox/index.vue";
import ShareProp from "./ShareProp/index.vue";
import DownLongGePu from "@/components/DownLongGePu.vue";
import Vsort from "@/directive/Vsort";
import { mapActions, mapGetters } from "vuex";
import { GEDAN_LIST_TYPE, PLAYNEWPAGENAME } from "@/utils/constant.js";
import { baseURL } from "@/utils/request";
import { copyText } from "@/utils/utils";
export default {
  name: "GeDanList",
  props: {
    id: {
      type: [String, Number],
      required: true,
    },
  },
  directives: { sort: Vsort },
  components: {
    DownLongGePu,
    JcBar,
    JcConfirmBox,
    ShareProp,
  },
  computed: {
    ...mapGetters({
      selfFingerprintId: "fingerprintId",
      selfUserId: "userId",
    }),
    isSelf() {
      return this.selfFingerprintId === this.fingerprintId || this.selfUserId === this.userId;
    },
    downUrl() {
      return `${baseUrl}/api/img?ids=${this.list.map((item) => item._id).join(",")}`;
    },
    gedanId() {
      if (this.id === "我的收藏") {
        return this.trueId;
      }
      return this.id;
    },
  },

  data() {
    return {
      error: false,
      errmsg: "",
      share: false,
      title: "",
      list: [],
      selectItemIndex: 0,
      dialogVisable: false,
      selectItemId: 0,

      userInfo: {
        avatarUrl: "",
        nickName: "",
      },
      copyurl: "",
      copyurlvisble: false,
      logSrc: process.env.VUE_APP_DINGFENGICON,
      bgSrc: process.env.VUE_APP_DENGTAICON,
      cavaPostSrc: "",
      sharePropVisable: false,
      prvePath: "/",
      trueId: "",
      fingerprintId: "",
      PLAYNEWPAGENAME,
      userId: "",
    };
  },

  activated() {
    this.init();
  },
  methods: {
    ...mapActions({
      collectorInit: "collector/init",
    }),
    init() {
      this.$jcLoading.show();
      return new Promise((resolve) => {
        this.list = [];
        if (this.id === "我的收藏") {
          this.collectorInit({ changed: true })
            .then((res) => {
              console.log(res);
              this.error = false;
              this.title = res.title;
              this.trueId = res.id;
              this.fingerprintId = res.fingerprintId;
              this.userId = res.userId;
              this.copyurl = `${location.origin}/#/gedanlist/${res.id}`;
              this.$store.dispatch("sgb/getItems", res.list).then((list) => {
                this.list = list.filter((item) => item);
                resolve(list);
              });
              resolve(res);
            })
            .finally(() => {
              this.$jcLoading.close();
            });
          return;
        }
        this.copyurl = `${location.origin}/#${this.$route.fullPath}`;
        gedanController
          .getGeDanDatailList(this.id, this.$route.query.shareUid || null)
          .then((res) => {
            if (res.error) {
              this.share = true;
              this.error = true;
              this.errmsg = res.title;
              resolve([]);
              return;
            }
            this.error = false;
            this.title = res.title;
            this.trueId = res.id;
            this.fingerprintId = res.fingerprintId;
            this.userId = res.userId;
            this.$store.dispatch("sgb/getItems", res.list).then((list) => {
              this.list = list.filter((item) => item);
              resolve(list);
            });
          })
          .finally(() => {
            this.$jcLoading.close();
          });
      });
    },
    handleDown() {
      alert({ type: "info", msg: "文件下载中...文件较大，请耐心等待" });
    },

    handleGetList(page, limit) {
      return new Promise((resolve) => {
        this.init().then(() => {
          resolve(this.list.slice((page - 1) * limit, (page - 1) * limit + limit));
        });
      });
    },
    handleRemove() {
      this.$jcLoading.show();
      gedanController
        .removeGeDanDatailList(this.trueId, this.selectItemId)
        .then(() => {
          this.list = this.list.filter((id) => id._id !== this.selectItemId);
          if (this.id === "我的收藏") {
            this.collectorInit();
          }
        })
        .finally(() => {
          this.$jcLoading.close();
        });
    },
    confirmChange(val) {
      if (!val) {
        this.dialogVisable = false;
      }
    },
    // 分享设置
    shareConfig() {
      this.sharePropVisable = true;
    },
    // 收藏为我的歌单
    saveAsMe() {
      const list = this.list.map((item) => item._id).join(",");
      gedanController
        .add(this.title + "_" + Date.now().toString().slice(9, 13), null, list)
        .then((id) => {
          this.$toast.success("收藏成功");
          this.$router.replace({ name: "GeDanList", params: { id } });
        })
        .catch(() => {
          // this.$toast.error('收藏失败')
        });
    },

    cavaSrc(src) {
      this.cavaPostSrc = src;
    },
    prev() {
      console.log(document.referrer);
      console.log(this.$router);
      if (this.prvePath === "/") {
        this.$router.replace("/");
      } else {
        this.$router.back();
      }
    },
    handleSortEnd(evt) {
      console.log(evt);
      console.log("oldIndex-->", evt.oldIndex); // element's old index within parent
      console.log("newIndex-->", evt.newIndex); // element's new index within parent

      const selectEl = this.list[evt.oldIndex];

      this.list.splice(evt.oldIndex, 1);
      this.list.splice(evt.newIndex, 0, selectEl);

      gedanController
        .updateGeDanDatailList(
          this.trueId,
          this.list.map((item) => item._id + "|" + item.type)
        )
        .then(() => {
          if (this.id === "我的收藏") {
            this.collectorInit();
          }
        });
    },
    toDetail(item) {
      if (item.type == GEDAN_LIST_TYPE.song) {
        this.$router.push({
          name: PLAYNEWPAGENAME,
          params: {
            id: item._id,
            gedanid: this.id,
            type: "gedan",
          },
        });
      }

      if (item.type == GEDAN_LIST_TYPE.jw) {
        this.$router.push({
          name: "JingWengRes",
          query: { id: item._id },
        });
      }
    },
    copyId() {
      try {
        copyText(this.id);
        this.$toast.success("复制成功 ID:" + this.id);
      } catch (error) {
        this.$toast.error("复制失败");
      }
    },
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.prvePath = from.fullPath;
    });
  },
};
</script>

<style scoped>
.share-btn {
  position: fixed;
  bottom: 50px;
  right: 0px;
  width: 30px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  border-top-left-radius: 15px;
  border-bottom-left-radius: 15px;
  font-size: 8px;
}
</style>
